import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Icon,
  Button,
  Divider,
  Tooltip,
  Popconfirm,
  Modal,
  message,
  Input,
} from 'antd';
import StandardTable from '../../../components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './ChannelMerchantsInfo.less';
import ChannelMerchantsInfoAddOrUpdate from './ChannelMerchantsInfoAddOrUpdate';

const { Item: FormItem } = Form;
const { confirm } = Modal;

@connect(({ channelMerchantsInfo, loading, user }) => ({
  channelMerchantsInfo,
  user,
  getListLoading: loading.effects['channelMerchantsInfo/getPageList'],
  getChildrenListLoading: loading.effects['channelMerchantsInfo/getChildrenList'],
  saveLoading: loading.effects['supplierInfo/saveInfo'],
  editLoading: loading.effects['channelMerchantsInfo/editInfo'],
  deleteByIdsLoading: loading.effects['supplierInfo/deleteByIds'],
  disablingByIdsLoading: loading.effects['supplierInfo/disablingByIds'],
  enablingByIdsLoading: loading.effects['supplierInfo/enablingByIds'],
}))
@Form.create()
class ChannelMerchantsInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      params: { page: 1, limit: 10 },
      channelMerchantsInfoList: {
        list: [],
        pagination: {
          current: 1,
          total: 0,
          pageSize: 1,
        },
      },
    };
  }

  // 页面初始化加载
  componentDidMount() {
    this.getList(this.state.params);
  }

  // 获取供应商信息表list数据
  getList(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'channelMerchantsInfo/getPageList',
      payload: params,
    });
  }

  // 条件查询list
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { params } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        page: params.page,
        limit: params.limit,
      };
      this.setState({
        params: values,
      });
      this.getList(values);
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { params } = this.state;
    form.resetFields();
    const searchParams = { page: params.page, limit: params.limit };
    this.setState({
      params: searchParams,
    });
    this.getList(searchParams);
  };

  // 新增修改供应商信息表信息
  handleSaveInfo = (fields, callback) => {
    const { dispatch } = this.props;
    const { id } = fields;
    let url = '';
    // 判断为新增
    if (id == null) {
      url = 'channelMerchantsInfo/saveInfo';
    }
    // 修改
    else {
      url = 'channelMerchantsInfo/editInfo';
    }
    dispatch({
      type: url,
      payload: fields,
    }).then(({ code }) => {
      if (code === 0) {
        callback('ok');
        this.getList(this.state.params);
      }
    });
  };

  // 删除供应商信息表
  deleteByIds(ids) {
    const { dispatch } = this.props;
    dispatch({
      type: 'channelMerchantsInfo/deleteByIds',
      payload: ids,
    }).then(({ code }) => {
      if (code === 0) {
        this.getList(this.state.params);
      }
    });
  }

  // 批量删除供应商信息表信息
  batchDelete() {
    const { selectedRows } = this.state;
    if (selectedRows.length === 0) {
      message.error('请选择删除数据行！！');
      return;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i++) {
      ids[i] = selectedRows[i].id;
    }
    const userPage = this;
    confirm({
      title: '您确定要删除所选数据行?',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        userPage.deleteByIds(ids);
      },
      onCancel() {},
    });
  }

  // 翻页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { params } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const searchParams = {
      ...params,
      ...filters,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    if (sorter.field) {
      searchParams.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({
      params: searchParams,
    });
    this.getList(searchParams);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 点击全部收起按钮事件
  handleUpTree = () => {
    this.setState({
      expandedRowsKeys: [],
      keys: []
    })
  };

  handleOnExpand = (expanded, record) => {
    const { dispatch } = this.props;
    if(!expanded)  return;  //如果是关闭就返回
    if(record.children && record.children.length > 0)  return;  //如果已经有数据就返回
    const id = record.id;
    dispatch({
      type: 'channelMerchantsInfo/getChildrenList',
      payload: id,
    })
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { params } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="渠道商名称">
              {getFieldDecorator('channelName', { initialValue: params.channelName })(
                <Input placeholder="请输入供应商名称" />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="联系人">
              {getFieldDecorator('contactsName', { initialValue: params.contactsName })(
                <Input placeholder="请输入联系人" />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="联系电话">
              {getFieldDecorator('contactNumber', { initialValue: params.contactNumber })(
                <Input placeholder="请输入联系电话" />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="身份证号">
              {getFieldDecorator('cardNumber', { initialValue: params.cardNumber })(
                <Input placeholder="请输入身份证号" />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      channelMerchantsInfo: { channelMerchantsInfoList },
      user: { currentUser },
      getListLoading,
      saveLoading,
      editLoading,
      deleteByIdsLoading,
      disablingByIdsLoading,
      enablingByIdsLoading,
      getChildrenListLoading
    } = this.props;
    const columns = [
      {
        title: '渠道商名称',
        dataIndex: 'channelName',
        key: 'channelName',
      },
      {
        title: '联系人',
        dataIndex: 'contactsName',
        key: 'contactsName',
      },
      {
        title: '联系电话',
        dataIndex: 'contactNumber',
        key: 'contactNumber',
      },
      {
        title: '身份证号',
        dataIndex: 'cardNumber',
        key: 'cardNumber',
      },
      {
        title: '会员级别',
        dataIndex: 'level',
        key: 'level',
      },
      {
        title: '状态',
        dataIndex: 'state',
        key: 'state',
        render: record => {
          switch (record) {
            case '2':
              return <span>开通</span>;
              break;
            case '3':
              return <span>禁用</span>;
              break;
            default:
              break;
          }
        },
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            {currentUser.permsSet && currentUser.permsSet.includes('base:channelMerchantsInfo:update') && (
              <Tooltip placement="bottom" title="编辑">
                <Icon
                  type="edit"
                  style={{ fontSize: '15px' }}
                  onClick={() => {
                    window.modal.current.getWrappedInstance().alertModal({
                      title: '编辑',
                      loading: 'channelMerchantsInfo/editInfo',
                      btnSubTitle: '修改',
                      component: ChannelMerchantsInfoAddOrUpdate,
                      record,
                      apply: this.handleSaveInfo,
                      width: 900,
                    });
                  }}
                />
              </Tooltip>
            )}
            {currentUser.permsSet && currentUser.permsSet.includes('base:channelMerchantsInfo:update') && (
              <Divider type="vertical" />
            )}
            {currentUser.permsSet && currentUser.permsSet.includes('base:channelMerchantsInfo:delete') && (
              <Popconfirm
                title="确认删除吗？"
                okText="删除"
                cancelText="取消"
                onConfirm={() => {
                  const ids = [];
                  ids[0] = record.id;
                  this.deleteByIds(ids);
                }}
              >
                <a>
                  <Tooltip placement="bottom" title="删除">
                    <Icon type="delete" style={{ fontSize: '15px', color: '#EE4000' }} />
                  </Tooltip>
                </a>
              </Popconfirm>
            )}
          </Fragment>
        ),
      },
    ];
    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
          <div className={styles.tableListOperator}>
            {currentUser.permsSet && currentUser.permsSet.includes('base:channelMerchantsInfo:save') && (
              <Button
                icon="plus"
                type="primary"
                onClick={() => {
                  window.modal.current.getWrappedInstance().alertModal({
                    title: '新增',
                    btnSubTitle: '新增',
                    loading: 'supplierInfo/saveInfo',
                    component: ChannelMerchantsInfoAddOrUpdate,
                    record: {},
                    apply: this.handleSaveInfo,
                    width: 900,
                  });
                }}
              >
                新增
              </Button>
            )}
            {currentUser.permsSet && currentUser.permsSet.includes('base:channelMerchantsInfo:delete') && (
              <Button
                icon="delete"
                type="danger"
                onClick={() => {
                  this.batchDelete();
                }}
              >
                批量删除
              </Button>
            )}
          </div>
          <StandardTable
            rowKey="id"
            defaultExpandAllRows={false}
            loading={
              getListLoading ||
              saveLoading ||
              editLoading ||
              deleteByIdsLoading ||
              disablingByIdsLoading ||
              enablingByIdsLoading ||
              getChildrenListLoading
            }
            selectedRows
            data={channelMerchantsInfoList}
            onExpand={this.handleOnExpand}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>
    );
  }
}
export default ChannelMerchantsInfo;
